<template>
  <el-dialog :visible.sync="visible" :title="disabled ? '能力展示' : '挂接'"  :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form key="1" v-if="!disabled" :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
     <el-form-item prop="pid" label="目录级别" class="menu-list">
        <el-popover v-model="menuListVisible" ref="menuListPopover" placement="bottom-start" trigger="click">
          <el-tree
            :data="catalogueTree"
            :props="{ label: 'name', children: 'children' }"
            node-key="id"
            ref="menuListTree"
            :highlight-current="true"
            :expand-on-click-node="false"
            accordion
            @current-change="menuListTreeCurrentChangeHandle">
          </el-tree>
        </el-popover>
        <el-input v-model="dataForm.type"  class="icon-input" v-popover:menuListPopover :readonly="true" placeholder="目录级别">
          <i v-if="dataForm.pid !== '0'" slot="suffix" @click.stop="deptListTreeSetDefaultHandle()" class="el-icon-circle-close el-input__icon"></i>
        </el-input>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="dataForm.name" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item label="服务地址" prop="visitUrl">
        <el-input v-model="dataForm.visitUrl" placeholder="服务地址"></el-input>
      </el-form-item>
      <el-form-item label="服务类型" prop="serviceType">
        <el-input v-model="dataForm.serviceType" placeholder="服务类型"></el-input>
      </el-form-item>
      <el-form-item label="版本号" prop="version">
        <el-input v-model="dataForm.version" placeholder="版本号"></el-input>
      </el-form-item>
      <el-form-item label="关键字" prop="keywords">
        <el-input v-model="dataForm.keywords" placeholder="关键字"></el-input>
      </el-form-item>
      <el-form-item label="摘要" prop="content">
        <el-input type="textarea" v-model="dataForm.content"></el-input>
      </el-form-item>
      <el-form-item label="发布单位" prop="unit">
        <el-select v-model="dataForm.unit" placeholder="请选择">
          <el-option v-for="unitItem in departmentSelects" :key="unitItem.data" :label="unitItem.label" :value="unitItem.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="简单介绍" prop="subtext">
        <el-input v-model="dataForm.subtext" placeholder="简单介绍"></el-input>
      </el-form-item>
      <!-- <el-form-item label="图标" prop="imgurl">
        <el-input v-model="dataForm.imgurl" placeholder="图标"></el-input>
      </el-form-item> -->
       <el-form-item prop="imgurl" :label="$t('menu.icon')" class="icon-list">
        <el-popover v-model="iconListVisible" ref="iconListPopover" placement="bottom-start" trigger="click" popper-class="mod-sys__menu-icon-popover">
          <div class="mod-sys__menu-icon-inner">
            <div class="mod-sys__menu-icon-list">
              <el-button
                v-for="(item, index) in iconList"
                :key="index"
                @click="iconListCurrentChangeHandle(item)"
                :class="{ 'is-active': dataForm.icon === item }">
                <svg class="icon-svg" aria-hidden="true"><use :xlink:href="`#${item}`"></use></svg>
              </el-button>
            </div>
          </div>
        </el-popover>
        <el-input v-model="dataForm.imgurl" v-popover:iconListPopover :readonly="true" class="icon-input" :placeholder="$t('menu.icon')"></el-input>
      </el-form-item>
      <el-form-item label="介绍" prop="context">
        <el-input type="textarea" v-model="dataForm.context"></el-input>
      </el-form-item>
      <el-form-item label="共享方式" prop="shareType">
        <el-select v-model="dataForm.shareType" placeholder="请选择">
          <el-option v-for="shareTypeItem in shareTypeArr" :key="shareTypeItem.data" :label="shareTypeItem.label" :value="shareTypeItem.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="共享形式 " prop="shareForm">
        <el-select v-model="dataForm.shareForm" placeholder="请选择">
          <el-option v-for="shareFormItem in shareFormArr" :key="shareFormItem.data" :label="shareFormItem.label" :value="shareFormItem.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="领域" prop="field">
        <el-select v-model="dataForm.field" placeholder="请选择">
          <el-option v-for="fieldItem in fieldArr" :key="fieldItem.data" :label="fieldItem.label" :value="fieldItem.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="场景" prop="scene">
        <el-select v-model="dataForm.scene" placeholder="请选择">
          <el-option v-for="sceneItem in sceneArr" :key="sceneItem.data" :label="sceneItem.label" :value="sceneItem.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        <el-select v-model="dataForm.deptId" placeholder="请选择">
          <el-option v-for="item in departmentSelects" :key="item.label" v-bind="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="使用要求" prop="useInfo">
        <!-- 富文本编辑器, 容器 -->
        <div id="J_quillEditor"></div>
        <!-- 自定义上传图片功能 (使用element upload组件) -->
        <el-upload
          :action="uploadUrl"
          :show-file-list="false"
          :before-upload="uploadBeforeUploadHandle"
          :on-success="uploadSuccessHandle"
          style="display: none;">
          <el-button ref="uploadBtn" type="primary" size="small">{{ $t('upload.button') }}</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <!-- 富文本编辑器, 容器 -->
        <div id="J_quillEditor"></div>
        <!-- 自定义上传图片功能 (使用element upload组件) -->
        <el-upload
          :action="uploadUrl"
          :show-file-list="false"
          :before-upload="uploadBeforeUploadHandle"
          :on-success="uploadSuccessHandle"
          style="display: none;">
          <el-button ref="uploadBtn" type="primary" size="small">{{ $t('upload.button') }}</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="是否推荐" prop="isUp">
        <el-select v-model="dataForm.isUp" placeholder="请选择">
          <el-option label="否" value="0"></el-option>
          <el-option label="是" value="1"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form key="2" class="detial-form" v-else  :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
     <el-form-item prop="pid" label="目录级别" class="menu-list">{{dataForm.type || '--'}}</el-form-item>
      <el-form-item label="名称" prop="name">
        {{dataForm.name || '--'}}

      </el-form-item>

      <el-form-item label="服务地址" prop="visitUrl">
        {{dataForm.visitUrl || '--'}}
      </el-form-item>
      <el-form-item label="服务类型" prop="serviceType">
        {{dataForm.serviceType || '--'}}
      </el-form-item>
      <el-form-item label="版本号" prop="version">
        {{dataForm.version || '--'}}
      </el-form-item>
      <el-form-item label="关键字" prop="keywords">
        {{dataForm.keywords || '--'}}
      </el-form-item>
      <el-form-item label="摘要" prop="content">
       {{dataForm.content || '--'}}
      </el-form-item>
      <el-form-item label="发布单位" prop="unit">
        {{dataForm.unit || '--'}}
      </el-form-item>
      <el-form-item label="简单介绍" prop="subtext">
        {{dataForm.subtext || '--'}}
      </el-form-item>

      <el-form-item prop="imgurl" :label="$t('menu.icon')" class="icon-list">
        <svg v-if="dataForm.imgurl" class="icon-svg" aria-hidden="true"><use :xlink:href="`#${dataForm.imgurl}`"></use></svg>
        <span v-else>--</span>
      </el-form-item>
      <el-form-item label="介绍" prop="context">
        {{dataForm.context || '--'}}
      </el-form-item>
      <el-form-item label="共享方式" prop="shareType">
       {{dataForm.shareType || '--'}}
      </el-form-item>
      <el-form-item label="共享形式 " prop="shareForm">
        {{dataForm.shareForm || '--'}}
      </el-form-item>
      <el-form-item label="领域" prop="field">
        {{dataForm.field || '--'}}
      </el-form-item>
      <el-form-item label="场景" prop="scene">
        {{dataForm.scene || '--'}}
      </el-form-item>
      <el-form-item label="部门" prop="deptId">
        {{dataForm.deptId || '--'}}
      </el-form-item>
      <el-form-item label="使用要求" prop="useInfo">
         <div v-html="dataForm.useInfo || '--'"></div>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
         <div v-html="dataForm.remarks || '--'"></div>
      </el-form-item>
      <el-form-item label="是否推荐" prop="isUp">
        {{+dataForm.isUp === 1 ? '是' : '否'}}
      </el-form-item>
    </el-form>
    <template slot="footer" v-if="!disabled">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import Cookies from 'js-cookie'
import 'quill/dist/quill.snow.css'
import Quill from 'quill'
import dictionaries from '@/utils/dictionaries'
import { mapState } from 'vuex'
import { getIconList } from '@/utils'

export default {
  data () {
    return {
      companyArr: dictionaries.companyArr,
      visible: false,
      quillEditor: null,
      quillEditorToolbarOptions: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block', 'image'],
        [{ header: 1 }, { header: 2 }],
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ script: 'sub' }, { script: 'super' }],
        [{ indent: '-1' }, { indent: '+1' }],
        [{ direction: 'rtl' }],
        [{ size: ['small', false, 'large', 'huge'] }],
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        [{ color: [] }, { background: [] }],
        [{ font: [] }],
        [{ align: [] }],
        ['clean']
      ],
      iconList: [],
      iconListVisible: false,
      unitArr: dictionaries.companyArr,
      sceneArr: dictionaries.sceneArr,
      fieldArr: dictionaries.fieldArr,
      shareFormArr: dictionaries.shareFormArr,
      shareTypeArr: dictionaries.shareTypeArr,
      uploadUrl: '',
      dataForm: {
        id: '',
        pid: '',
        visitUrl: '',
        name: '',
        serviceType: '',
        content: '',
        version: '',
        keywords: '',
        unit: '',
        isDelete: '',
        creator: '',
        createDate: '',
        updater: '',
        subtext: '',
        imgurl: '',
        context: '',
        updateDate: '',
        type: '',
        shareType: '',
        onlineDate: '',
        goal: '',
        shareForm: '',
        field: '',
        scene: '',
        rank: '',
        deptId: '',
        useInfo: '',
        remarks: '',
        isUp: ''
      }
    }
  },
  props: {
    disabled: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState(['catalogueTree']),
    ...mapState(['departmentSelects']),
    dataRule () {
      const validateremarks = (rule, value, callback) => {
        if (this.quillEditor.getLength() <= 1) {
          return callback(new Error(this.$t('validate.required')))
        }
        callback()
      }
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        serviceType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        content: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        version: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        keywords: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        unit: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {

  },
  methods: {
    init () {
      this.visible = true
      this.$nextTick(() => {
        if (!this.disabled) {
          if (this.quillEditor) {
            this.quillEditor.deleteText(0, this.quillEditor.getLength())
          } else {
            this.quillEditorHandle()
          }
        }
        this.iconList = getIconList()
        this.$refs.dataForm && this.$refs.dataForm.resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 图标, 选中
    iconListCurrentChangeHandle (icon) {
      this.dataForm.imgurl = icon
      this.iconListVisible = false
    },
    // 上级菜单树, 选中
    menuListTreeCurrentChangeHandle (data) {
      this.dataForm.pid = data.id
      this.dataForm.type = data.name
      this.menuListVisible = false
    },
    // 上级菜单树, 设置默认值
    deptListTreeSetDefaultHandle () {
      this.dataForm.pid = '0'
      this.dataForm.type = '目录级别'
    },
    // 获取信息
    getInfo () {
      this.$http.get('/ability/bsabilitylayer/' + this.dataForm.id).then(({ data: res }) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.quillEditor.root.innerHTML = this.dataForm.remarks
      }).catch(() => {})
    },
    // 富文本编辑器
    quillEditorHandle () {
      this.quillEditor = new Quill('#J_quillEditor', {
        modules: {
          toolbar: this.quillEditorToolbarOptions
        },
        theme: 'snow'
      })
      // 自定义上传图片功能 (使用element upload组件)
      this.uploadUrl = window.SITE_CONFIG.apiURL + '/sys/oss/upload?token=' + Cookies.get('token')
      this.quillEditor.getModule('toolbar').addHandler('image', () => {
        this.$refs.uploadBtn.$el.click()
      })
      // 监听内容变化，动态赋值
      this.quillEditor.on('text-change', () => {
        this.dataForm.remarks = this.quillEditor.root.innerHTML
      })
    },
    // 上传图片之前
    uploadBeforeUploadHandle (file) {
      if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
        this.$message.error('只支持jpg、png、gif格式的图片！')
        return false
      }
    },
    // 上传图片成功
    uploadSuccessHandle (res, file, fileList) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.quillEditor.insertEmbed(this.quillEditor.getSelection().index, 'image', res.data.src)
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs.dataForm.validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/ability/bsabilitylayer/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { leading: true, trailing: false })
  }
}
</script>
<style lang="scss" scoped>
.icon-input ::v-deep  .el-input__inner {
  cursor: pointer;
}
.detial-form ::v-deep {
  .el-form-item {
    margin-bottom: 0px;
    line-height: 32px;
  }
  .el-form-item__label {
    line-height: 32px;
  }
  .el-form-item__content {
    line-height: 32px;
  }
}
</style>

<style lang="scss">
.mod-sys__menu {
  .menu-list,
  .icon-list {
    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }
  &-icon-popover {
    width: 458px;
    overflow: hidden;
  }
  &-icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }
  &-icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;
    > .el-button {
      padding: 8px;
      margin: 8px 0 0 8px;
      > span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}
</style>
